package com.kevin.codec;

import com.kevin.core.Header;
import com.kevin.core.RpcProtocol;
import com.kevin.serial.ISerializer;
import com.kevin.serial.SerializerManager;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class RpcEncoder extends MessageToByteEncoder<RpcProtocol> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RpcProtocol rpcProtocol, ByteBuf byteBuf) throws Exception {

        System.out.println("进入编码器");
        Header header = rpcProtocol.getHeader();
        Object data = rpcProtocol.getContent();
        byteBuf.writeShort(header.getMagic());
        byteBuf.writeByte(header.getSerialtype());
        byteBuf.writeByte(header.getReqType());
        byteBuf.writeLong(header.getSessionId());

        //将对象根据序列化类型进行序列化
        ISerializer serializer = SerializerManager.getSerializer(header.getSerialtype());
        byte[] dataBytes =serializer.serialize(data);
        byteBuf.writeInt(dataBytes.length);
        byteBuf.writeBytes(dataBytes);
        System.out.println("进入编码器结束");
    }
}
